<?php

namespace App\Http\Controllers\Site\Custom\Purchaser;

use App\B2BProject\Site\HelperControllerBuildTrait;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class MyProviderController extends Controller
{
    use HelperControllerBuildTrait;

    public function getIndex(Request $request)
    {
        $request->query->set('page', $request->query('page', $request->page));
        $request->query->set('pageSize', $request->query('pageSize', $request->pageSize));

        $authorizations = \Auth::user()->purchaserAuthorizationRequests()->display();

        if ($start = $request->query('startTime')) {
            $authorizations->where('authorize_stop', '>=', date('Y-m-d', strtotime($start)));
        }

        if ($end = $request->query('endTime')) {
            $authorizations->where('authorize_stop', '<=', date('Y-m-d', strtotime($end)));
        }

        if ($name = $request->query('name')) {
            $authorizations->whereHas('provider.information', function ($query) use ($name) {
                $query->where('company', 'like', "%$name%");
            });
        }

        $authorizations = $authorizations->orderBy('created_at',
            'desc')->paginate($request->query('pageSize', 7));

        if ($request->ajax()) {
            $data = [];

            foreach ($authorizations as $authorization) {
                $data[] = [
                    'id'          => $authorization->id,
                    'companyname' => $authorization->provider->information->company,
                    'buyername'   => $authorization->contact_name,
                    'state'       => ['停止授权', '合作中', '过期'][$authorization->getAuthorizationStatus()],
                    'applydate'   => date('Y-m-d', strtotime($authorization->created_at)),
                    'adoptdate' => date('Y-m-d', strtotime($authorization->authorize_start)),
                    'enddate'     => date('Y-m-d', strtotime($authorization->authorize_stop)),
                    'amount'      => $authorization->licensedGoods()->count(),
                ];
            }

            return response()->json([
                'data'           => $data,
                'pagingConfData' => [
                    'page'     => $authorizations->currentPage(),
                    'pageSize' => $request->query('pageSize'),
                    'total'    => $authorizations->total(),
                ],
            ]);
        }

        return view('host/custom/purchaser/my-provider/index');
    }
}
